Write-Host "开始部署 SmartResume-AI..." -ForegroundColor Green

# 创建部署脚本内容
$deployScript = @'
#!/bin/bash
echo "开始部署 SmartResume-AI..."

# 安装Docker
if ! command -v docker &> /dev/null; then
    echo "安装Docker..."
    yum update -y
    yum install -y yum-utils
    yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    yum install -y docker-ce docker-ce-cli containerd.io
    systemctl start docker
    systemctl enable docker
fi

# 安装Docker Compose
if ! command -v docker-compose &> /dev/null; then
    echo "安装Docker Compose..."
    curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
    ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
fi

# 克隆项目
PROJECT_DIR="/opt/smartresume-ai"
if [ -d "$PROJECT_DIR" ]; then
    cd $PROJECT_DIR
    git pull origin main
else
    git clone https://github.com/Miku-da-you/SmartResume-AI.git $PROJECT_DIR
    cd $PROJECT_DIR
fi

# 配置环境变量
cp ai-server/.env.example ai-server/.env
sed -i 's/your_app_id_here/a00be55e/g' ai-server/.env
sed -i 's/your_api_secret_here/Y2JhMGNiMjU2MTg4NDYyM2EwMzUwNTYy/g' ai-server/.env
sed -i 's/your_api_key_here/128c4b382bbc366eda1e59d222725a15/g' ai-server/.env

# 配置防火墙
if systemctl is-active --quiet firewalld; then
    firewall-cmd --permanent --add-port=80/tcp
    firewall-cmd --permanent --add-port=8080/tcp
    firewall-cmd --permanent --add-port=5005/tcp
    firewall-cmd --reload
fi

# 部署服务
docker-compose down
docker-compose build
docker-compose up -d

echo "部署完成！访问地址: http://117.72.205.240"
docker-compose ps
'@

# 保存脚本到临时文件
$deployScript | Out-File -FilePath "deploy_temp.sh" -Encoding UTF8

Write-Host "传输部署脚本到服务器..." -ForegroundColor Yellow

# 传输脚本
& ".\pscp.exe" -pw "Qijianxin1!" "deploy_temp.sh" "root@117.72.205.240:/root/deploy.sh"

if ($LASTEXITCODE -eq 0) {
    Write-Host "脚本传输成功，开始执行部署..." -ForegroundColor Green
    
    # 执行部署
    & ".\plink.exe" -ssh -pw "Qijianxin1!" "root@117.72.205.240" -batch "chmod +x /root/deploy.sh && /root/deploy.sh"
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "部署完成！" -ForegroundColor Green
        Write-Host "访问地址: http://117.72.205.240" -ForegroundColor Cyan
    } else {
        Write-Host "部署执行失败" -ForegroundColor Red
    }
} else {
    Write-Host "脚本传输失败" -ForegroundColor Red
}

# 清理临时文件
Remove-Item "deploy_temp.sh" -Force -ErrorAction SilentlyContinue